package com.cn.xc.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cn.bean.ValiBean;

/**
 * FUN: validateCode tools class
 * 
 * @author sushy 2015年1月26日
 */
public final class ValiCodeUtil {

	private final static String VALID_CODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	
	/**
	 * //#  get validateCode
	 * @param response
	 * @param session
	 * @param valiBean validate property 
	 * @throws IOException
	 */
	public static void getValidateCode(HttpServletResponse response, HttpSession session, ValiBean valiBean)
			throws IOException {
		if (valiBean == null) {
			return;
		}
		int charNum = valiBean.getCharNum();
		int width = valiBean.getWidth();
		int heght = valiBean.getHeght();
		int fontSize = valiBean.getFontSize(); 
		
		BufferedImage image = new BufferedImage(width, heght, BufferedImage.TYPE_INT_RGB);
		Graphics gp = image.getGraphics();
		Random r = new Random();
		gp.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
		gp.fillRect(0, 0, width, heght);
		String valiCode = getCode(charNum);
		session.setAttribute("validateCode", valiCode);
		gp.setColor(new Color(0, 0, 0));
		gp.setFont(new Font(null, Font.BOLD, fontSize));
		gp.drawString(valiCode, 5, 25);
		for (int i = 0; i < 10; i++) {
			gp.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(255)));
			gp.drawLine(r.nextInt(width), r.nextInt(heght), r.nextInt(width), r.nextInt(heght));
		}
		response.setContentType("image/jpeg");
		OutputStream ops = response.getOutputStream();
		ImageIO.write(image, "jpeg", ops);
		ops.close();
	}

	/**
	 * get random string, acoding to size
	 * 
	 * @param size
	 * @return
	 */
	private static String getCode(int size) {
		StringBuilder code = new StringBuilder();
		Random r = new Random();
		for (int i = 0; i < size; i++) {
			code.append(VALID_CODE.charAt(r.nextInt(VALID_CODE.length())));
		}
		return code.toString();
	}

}
